package com.hardy.Thread;

import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Author: fuxh3@lenovo.com
 * Date: Created in 2018/2/24 0024
 */
public class CyclicBarrierTest {
    public static void main(String[] args) {
        ExecutorService service = Executors.newCachedThreadPool();
        final CyclicBarrier cb = new CyclicBarrier(3);
        for(int i=0;i<3;i++){
            Runnable runnable = new Runnable(){
                public void run(){
                    try {
                        Thread.sleep((long)(Math.random()*10000));
                        System.out.println("thread " + Thread.currentThread().getName() +
                                                        "ji jiang dao da ji he di dian 1,dang qian yi you " + (cb.getNumberWaiting()+1) + "ge yi jing dao da，" + (cb.getNumberWaiting()==2?"dou dao qi le，ji xu zou a":"zheng zai deng hou"));
                        cb.await();

                        Thread.sleep((long)(Math.random()*10000));
                        System.out.println("thread " + Thread.currentThread().getName() +
                                                        "ji jiang dao da ji he di dian 2,dang qian yi you " + (cb.getNumberWaiting()+1) + "ge yi jing dao da，" + (cb.getNumberWaiting()==2?"dou dao qi le，ji xu zou a":"zheng zai deng hou"));
                        cb.await();
                        Thread.sleep((long)(Math.random()*10000));
                        System.out.println("thread " + Thread.currentThread().getName() +
                                                        "ji jiang dao da ji he di dian 3,dang qian yi you " + (cb.getNumberWaiting() + 1) + "ge ji jing dao da，" + (cb.getNumberWaiting()==2?"dou dao qi le，ji xu zou a":"zheng zai deng hou"));
                        cb.await();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };
            service.execute(runnable);
        }
        service.shutdown();
    }
}
